﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//using Portal.Game.DAL;
using Portal.Core.DAL;
using System.ComponentModel;
using Portal.BO.Editoral.Category;
using Portal.User.Security;
using Portal.BO.Editoral.Statistic;
using Portal.BO.Editoral.Newsedit;
using Portal.BO.Editoral.CommentManagement;


namespace Portal.BO.Editoral.Newslist
{
	//[AjaxPro.AjaxNamespace("LogActionAjax")]
	public static class NewslistHelper
	{


		[DataObjectMethod(DataObjectMethodType.Select)]
		public static DataTable GetNewslist(string strWhere, int PageSize, int StartRow, bool isFistPage)
		{
			//Lay gia tri mode list de xu ly
			if (strWhere == null)
				strWhere = "";
			if (isFistPage)
			{
				StartRow = 0;
			}

			string cpmode = "";
			if (HttpContext.Current.Request.QueryString["cpmode"] != null)
				cpmode = HttpContext.Current.Request.QueryString["cpmode"].ToString();
			DataTable objresult;
			int intPageNum = StartRow / PageSize + 1;
			//lay duoc du lieu cua tat ca nhung thang co trang thai la status can lay
			using (MainDB objdb = new MainDB())
			{
				//objresult = objdb.NewsCollection.GetPageAsDataTable(intPageNum, PageSize, strWhere, "News_ModifiedDate DESC"); ;
                objresult = objdb.StoredProcedures.News_GetListNew(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name, StartRow.ToString(), PageSize.ToString(), "[News].News_PublishDate DESC");
			}
			return objresult;
		}

		/// <summary>
		/// Check whether current user can edit the news
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public static bool isHasPermission(HttpContext context)
		{
			if (context.Request.QueryString["NewsRef"] == null || context.Request.QueryString["NewsRef"] == string.Empty)
				return true;
			else
			{
				string cpMode = context.Request.QueryString["cpmode"];
				if (!string.IsNullOrEmpty(cpMode))
				{
					if (cpMode.Contains(",")) cpMode = cpMode.Substring(cpMode.IndexOf(",") + 1);
					cpMode = cpMode.ToLower();

					long newsId = long.Parse(context.Request.QueryString["NewsRef"]);
					string userName = context.User.Identity.Name;
					if (!string.IsNullOrEmpty(userName) && newsId != 0)
					{
						MainSecurity objsecu = new MainSecurity();
						//Role objrole = objsecu.GetRole(context.User.Identity.Name);

						NewsRow newsRow = NewsEditHelper.GetNewsInfo_News(newsId, false);
						if (newsRow != null)
						{
							Permission permission = objsecu.GetPermission(userName);
							MainDB db = new MainDB();
							bool toReturn = false;
							switch (cpMode)
							{
								case "templist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.LuuTam
										&& db.StoredProcedures.News_isLastAccessUser(newsId, userName);
									break;
								case "editwaitlist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.ChoBienTap
										&& permission.isBien_Tap_Bai
										&& db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
									break;
								case "editinglist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.NhanBienTap
										&& permission.isBien_Tap_Bai
										&& db.StoredProcedures.News_isLastAccessUser(newsId, userName);
									break;
								case "approvalwaitlist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.ChoDuyet && permission.isDuyet_Bai
										&& db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
									break;
                                case "sendapprovallist":
                                    toReturn = newsRow.News_Status == (byte)NewsStatus.ChoDuyet && permission.isDuyet_Bai
                                        && db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
                                    break;
								case "approvinglist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.NhanDuyet && permission.isDuyet_Bai
										&& db.StoredProcedures.News_isLastAccessUser(newsId, userName);
									break;
								case "publishedlist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.XuatBan && permission.isXuat_Ban_Bai
										&& db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
									break;
                                case "publishbycat":
                                    toReturn = newsRow.News_Status == (byte)NewsStatus.XuatBan && permission.isXuat_Ban_Bai
                                        && db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
                                    break;
								case "removedlist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.GoBo && permission.isXuat_Ban_Bai
										&& db.StoredProcedures.News_isHasPermissionEdit(newsId, CategoryHelper.GetCatIDByUser());
									break;
								case "backlist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.TraLai
										&& db.StoredProcedures.News_isLastAccessUser(newsId, userName);
									break;
								case "dellist":
									toReturn = newsRow.News_Status == (byte)NewsStatus.XoaTam
										&& db.StoredProcedures.News_isLastAccessUser(newsId, userName);
									break;
							}
							return toReturn;
						}
					}
				}
			}
			return false;
		}

		/// <summary>
		/// Ham lay Action hien thoi cua tin
		/// </summary>
		/// <param name="_news_id">ID cua tin</param>
		/// <returns></returns>
		public static ActionRow getLastestAction(long _news_id)
		{
			ActionRow[] _arows;
			using (MainDB objDb = new MainDB())
			{
				_arows = objDb.ActionCollection.GetTopAsArray(1, "News_ID=" + _news_id, "CreateDate DESC");
			}
			if (_arows.Length > 0)
				return _arows[0];
			else
				return null;
		}
		public static int getLastestStatus(long _news_id)
		{
			ActionRow ac = getLastestAction(_news_id);
			if (ac != null && !ac.IsActionTypeNull)
				return getLastestAction(_news_id).ActionType;

			return 0;
		}
		private static string getReceiver(long _news_id)
		{
			return getLastestAction(_news_id).Reciver_ID;
		}
		private static string getSender(long _news_id)
		{
			return getLastestAction(_news_id).Sender_ID;
		}
		public static int GetRowsCount(string strWhere, bool isFistPage)
		{
			if (strWhere == null)
				strWhere = "";
			string cpmode = HttpContext.Current.Request.QueryString["cpmode"].ToString();
			DataTable objresult;
			using (MainDB objdb = new MainDB())
			{
				objresult = objdb.StoredProcedures.News_GetListNewNumRow(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name);
			}
			return (int)objresult.Rows[0][0];
		}
		[DataObjectMethod(DataObjectMethodType.Select)]
		public static DataTable getPage(int numPage)
		{
			int intPagenum = numPage;
			DataTable objTb = new DataTable();
			objTb.Columns.Add(new DataColumn("Text", typeof(string)));
			objTb.Columns.Add(new DataColumn("Value", typeof(string)));
			for (int i = 1; i <= intPagenum; i++)
			{
				DataRow myRow = objTb.NewRow();
				myRow["Text"] = i.ToString();
				myRow["Value"] = Convert.ToString(i - 1);
				objTb.Rows.Add(myRow);
			}
			if (intPagenum == 0)
			{
				DataRow myRow = objTb.NewRow();
				myRow["Text"] = "1";
				myRow["Value"] = "0";
				objTb.Rows.Add(myRow);
			}
			return objTb;
		}
		[DataObjectMethod(DataObjectMethodType.Update)]
		public static void UpdateNewsRow(long _news_id, int _news_status, string _selected_id)
		{
			if (_selected_id == "" || _selected_id == null)
				newsupdate(_news_id, _news_status);
			else
			{
				//truong hop chuyen trang thai cho tat ca cac tin duoc select
				string[] strnews_ids = _selected_id.Split(",".ToCharArray());
				foreach (string strid in strnews_ids)
				{
					long intNid = Convert.ToInt64(strid);
					newsupdate(intNid, _news_status);
				}
			}
		}

		public static DataTable GetActionByNewsId(string news_id)
		{
			using (MainDB objDb = new MainDB())
			{
				return objDb.StoredProcedures.GetActionByNewsId(news_id);
			}
		}

		public static string GetReciver_IDForDisApproveList(string news_id)
		{
			string sReturn = "";
			DataTable dt;
			using (MainDB objDb = new MainDB())
			{
				dt = objDb.StoredProcedures.GetSenderActionAprroving(news_id);
			}

			if (dt.Rows.Count == 0)
			{
				dt = GetActionByNewsId(news_id);
				if (dt.Rows.Count == 2)
				{
					sReturn = dt.Rows[1]["Sender_ID"].ToString();
				}
				else
					if (dt.Rows.Count > 2)
					{
						sReturn = dt.Rows[2]["Sender_ID"].ToString();
					}

			}
			else
			{
				sReturn = dt.Rows[0]["Sender_ID"].ToString();
			}

			return sReturn;
		}


		[DataObjectMethod(DataObjectMethodType.Update)]
		public static void UpdateNewsRow(long _news_id, int _news_status, string _selected_id, bool blnIsFocus, int intNewMode, bool isUpdate)
		{
			if (isUpdate == false)//Truong hop gui len
			{
				if (_selected_id == "" || _selected_id == null)
					newsupdate(_news_id, _news_status);
				else
				{
					//truong hop chuyen trang thai cho tat ca cac tin duoc select
					string[] strnews_ids = _selected_id.Split(",".ToCharArray());
					foreach (string strid in strnews_ids)
					{
						long intNid = Convert.ToInt64(strid);
						newsupdate(intNid, _news_status);
					}
				}
			}
			else //Truong hop edit truc tiep tren row
			{
				newsupdate(_news_id, blnIsFocus, intNewMode);
			}
		}


		private static void newsupdate(long _news_id, bool blnIsFocus, int intNewMode)
		{
			MainDB objDb = new MainDB();
			objDb.BeginTransaction();
			try
			{
				NewsRow objRow;
				NewsPublishedRow publishedRow = null;
				bool IsPublished = false;
				String cpmode = HttpContext.Current.Request.QueryString["cpmode"];
				if (cpmode.IndexOf("publishedlist") >= 0 || cpmode.IndexOf("removedlist") >= 0)
					IsPublished = true;

				//using (MainDB objDb = new MainDB())
				//{
				objRow = objDb.NewsCollection.GetByPrimaryKey(_news_id);

				if (IsPublished)
					publishedRow = objDb.NewsPublishedCollection.GetByPrimaryKey(_news_id);
				//}
				if (objRow != null)
				{
					//thuc hien doi trang thai cua tin - luu thong tin modified thanh ngay gio hien tai.
					//objRow.News_Status = _news_status;
					objRow.News_isFocus = blnIsFocus;
					objRow.News_Mode = intNewMode;
					objRow.News_ModifiedDate = DateTime.Now;

					if (IsPublished && publishedRow != null)
					{
						publishedRow.News_isFocus = blnIsFocus;
						publishedRow.News_Mode = intNewMode;
						publishedRow.News_ModifedDate = DateTime.Now;
					}

					//using (MainDB objDb = new MainDB())
					//{
					objDb.NewsCollection.Update(objRow);

					if (IsPublished && publishedRow != null)
						objDb.NewsPublishedCollection.Update(publishedRow);
					//}
				}

				// Commit Transaction
				objDb.CommitTransaction();
			}
			catch (Exception ex)
			{
				objDb.RollbackTransaction();
			}
			finally
			{
				objDb.Close();
			}



		}

		private static void newsupdate(long _news_id, int _news_status)
		{
			NewsRow objRow;
			int old_news_status = -1;
			int _cat_id = -1;

			MainDB objDb = new MainDB();
			objDb.BeginTransaction();
            string strAction = "";
			try
			{
				objRow = objDb.NewsCollection.GetByPrimaryKey(_news_id);
                string _news_title = objRow.News_Title.Trim();
				old_news_status = objRow.News_Status;
				_cat_id = objRow.Cat_ID;
                int type_log_action = LogAction.LogType_BaiViet;

				if (objRow != null)
				{
					//thuc hien doi trang thai cua tin - luu thong tin modified thanh ngay gio hien tai.
					objRow.News_Status = _news_status;
					objRow.News_ModifiedDate = DateTime.Now;
                    objRow.News_Approver = HttpContext.Current.User.Identity.Name;
					//thuc hien luu thong tin vao action.
					ActionRow objArow = new ActionRow();
					//Gui len. Neu la xoa tam thi khong luu action
					if (_news_status == 1)
					{
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " gửi bài chờ biên tập";
						objArow.ActionType = 1;
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_GuiChoBT + " bởi " + HttpContext.Current.User.Identity.Name;
					}
					if (_news_status == 2)
					{
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " gửi bài chờ duyệt";
						objArow.ActionType = 2;
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_GuiChoBT + " bởi " + HttpContext.Current.User.Identity.Name;
					}

					NewsPublishedRow objpublishRow = new NewsPublishedRow();
					if (_news_status == 3)
					{
						objRow.News_Approver = HttpContext.Current.User.Identity.Name;
						if (objRow.IsNews_PublishDateNull == false && objRow.News_PublishDate.Year != 9999 && objRow.News_PublishDate.Year != 2000)
							objRow.News_PublishDate = DateTime.Now;

						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " xuất bản bài";
						objArow.ActionType = 3;
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_XB + " bởi " + HttpContext.Current.User.Identity.Name;
                        type_log_action = LogAction.LogType_BaiViet_XB;

						//thuc hien chuyen du lieu qua bang newspublished

						objpublishRow.News_ID = objRow.News_ID;
						objpublishRow.Cat_ID = objRow.Cat_ID;
						objpublishRow.News_Subtitle = objRow.News_Subtitle;
						objpublishRow.News_Title = objRow.News_Title;
						objpublishRow.News_Image = objRow.News_Image;
						objpublishRow.News_Source = objRow.News_Source;
						objpublishRow.News_InitContent = objRow.News_InitialContent;
						objpublishRow.News_Content = objRow.News_Content;
						objpublishRow.News_Athor = objRow.News_Author;
						objpublishRow.News_Approver = objRow.News_Approver;
						objpublishRow.News_Status = 3;

						if (objRow.IsNews_PublishDateNull == true || objRow.News_PublishDate.Year == 9999 || objRow.News_PublishDate.Year == 2000)
						{
							objRow.News_PublishDate = DateTime.Now;
						}
						objpublishRow.News_PublishDate = objRow.News_PublishDate;

						objpublishRow.News_isFocus = objRow.News_isFocus;
						objpublishRow.News_Mode = objRow.News_Mode;
						objpublishRow.isComment = objRow.isComment;
						objpublishRow.isUserRate = objRow.isUserRate;
						objpublishRow.Template = objRow.Template;
						objpublishRow.Icon = objRow.Icon;
						//objpublishRow.News_Relation = objRow.News_Relation;

					}
					if (_news_status == 5)
					{
						ActionRow objLastestArow = NewslistHelper.getLastestAction(Convert.ToInt64(_news_id));
						objArow.Reciver_ID = objLastestArow.Sender_ID;
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " trả lại bài";
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_TraLai + " bởi " + HttpContext.Current.User.Identity.Name;
						objArow.ActionType = getLastestStatus(_news_id);

                        if (old_news_status == 3) type_log_action = LogAction.LogType_BaiViet_XB;
					}
					//xoa tam
					if (_news_status == 6)
					{
						objArow.Reciver_ID = HttpContext.Current.User.Identity.Name;
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " xoá tạm bài";
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_XoaTam + " bởi " + HttpContext.Current.User.Identity.Name;
						objArow.ActionType = getLastestStatus(_news_id);
					}
					//gui bai tu backlist len
					if (_news_status == -1)
					{
						int intLastStaus = getLastestStatus(_news_id);
						objArow.Reciver_ID = HttpContext.Current.User.Identity.Name;
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " gửi bài";
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_GuiBai + " bởi " + HttpContext.Current.User.Identity.Name;
						objRow.News_Status = intLastStaus;
						objArow.ActionType = intLastStaus;
					}
					if (_news_status == 7)
					{
						int intLastStaus = getLastestStatus(_news_id);
						objArow.ActionType = intLastStaus;
						objArow.Comment_Title = HttpContext.Current.User.Identity.Name + " gỡ bỏ bài";
                        strAction = "<b>" + _news_title.Replace("'", "") + "</b> " + LogAction.LogAction_GoBai + " bởi " + HttpContext.Current.User.Identity.Name;
                        type_log_action = LogAction.LogType_BaiViet_XB;

						// Neu la go bo thi go luon o bang NewsPublished
						//using (MainDB objDb = new MainDB())
						//{
						objpublishRow = objDb.NewsPublishedCollection.GetByPrimaryKey(_news_id);
						if (objpublishRow != null)
						{
							objDb.NewsPublishedCollection.DeleteByPrimaryKey(_news_id);
						}
						//}
					}

					objArow.News_ID = _news_id;
					objArow.Sender_ID = HttpContext.Current.User.Identity.Name;

					objArow.CreateDate = DateTime.Now;

					//if (_news_status != 6)
					objDb.ActionCollection.Insert(objArow);
					objDb.NewsCollection.Update(objRow);
					if (_news_status == 3)
					{
						objDb.NewsPublishedCollection.Insert(objpublishRow);
					}

					// Commit Transaction
					objDb.CommitTransaction();
                    /* tiennv 24-05-2010 : Insert vao memcache 
                    LogAction.InsertMemCache(HttpContext.Current.User.Identity.Name, DateTime.Now, strAction, type_log_action, objRow.News_ID);
					*/
                    #region Insert vao bang LogInfo để thống kê
                    //Log objLog = new Log();

                    //if (old_news_status != -1 && old_news_status != _news_status && _cat_id != -1)
                    //{
                    //    string strUser_Id = HttpContext.Current.User.Identity.Name;
                    //    if (_news_status == 1)
                    //    {
                    //        // Đối với bài chờ biên tập
                    //        objLog.UpdateLogInfo((int)CountKey.Category_Wait_Edit_Content, _cat_id.ToString());
                    //        objLog.UpdateLogInfo((int)CountKey.User_Wait_Edit_Content, strUser_Id);
                    //    }
                    //    else if (_news_status == 2)
                    //    {
                    //        // Đối với bài chờ duyet
                    //        objLog.UpdateLogInfo((int)CountKey.Category_Wait_Approve_Content, _cat_id.ToString());
                    //        objLog.UpdateLogInfo((int)CountKey.User_Wait_Approve_Content, strUser_Id);
                    //    }
                    //    else if (_news_status == 3)
                    //    {
                    //        // Đối với bài đã xuất bản
                    //        objLog.UpdateLogInfo((int)CountKey.Category_Approved_Content, _cat_id.ToString());
                    //        objLog.UpdateLogInfo((int)CountKey.User_Approved_Content, strUser_Id);
                    //    }
                    //}
					#endregion
				}

			}
			catch (Exception ex)
			{
				objDb.RollbackTransaction();
			}
			finally
			{
				objDb.Close();
			}

		}
		#region Delete method
		[DataObjectMethod(DataObjectMethodType.Delete)]
		public static void DelNews(string _selected_id)
		{
			if (_selected_id.IndexOf(",") <= 0)
			{
				FileHelper.DeleteFolder(HttpContext.Current.Server.MapPath(@"\portal\images") + @"\uploaded\share\" + _selected_id);

				try
				{
					long intid = Convert.ToInt64(_selected_id);
					using (MainDB objDB = new MainDB())
					{

						objDB.NewsCollection.DeleteByPrimaryKey(intid);

					}
				}
				catch { }
			}
			else
			{
				string[] objTempSel = _selected_id.Split(',');
				foreach (string temp in objTempSel)
				{
					// DeleteFile(temp.Trim());
					FileHelper.DeleteFolder(HttpContext.Current.Server.MapPath(@"\portal\images") + @"\uploaded\share\" + temp);
				}
				try
				{
					using (MainDB objDB = new MainDB())
					{
						objDB.NewsCollection.Delete("News_ID in (" + _selected_id + ")");
					}
				}
				catch { }
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="_sWhere"></param>
		private static void DeleteFile(string _news_id)
		{
			string strFolder = "images/uploaded/";
			FileHelper.delImgFolder(strFolder, "Share/" + _news_id);
		}



		#endregion
		[DataObjectMethod(DataObjectMethodType.Update)]
		public static void UpdateFeedbackRow(long _news_id, int _news_status, int _action_type, string _action_title, string _action_content)
		{
			string strcpmode = HttpContext.Current.Request.QueryString["cpmode"].ToString();
			NewsRow objrow;
			using (MainDB objDb = new MainDB())
			{
				objrow = objDb.NewsCollection.GetByPrimaryKey(_news_id);
			}
			if (objrow != null)
			{
				objrow.News_Status = _news_status;
				objrow.News_ModifiedDate = DateTime.Now;

				ActionRow objArow = new ActionRow();
				objArow.ActionType = _action_type;
				objArow.News_ID = _news_id;


				objArow.Sender_ID = HttpContext.Current.User.Identity.Name;
				if (strcpmode.IndexOf("removedlist") >= 0)
				{
					string strSender = GetReciver_IDForDisApproveList(_news_id.ToString());
					objArow.Reciver_ID = strSender;
				}
				else
				{
					string strSender = getSender(_news_id);
					objArow.Reciver_ID = strSender;
				}

				if (_action_title != "")
					objArow.Comment_Title = _action_title;
				else
					objArow.Comment_Title = " Trả lại tin";
				objArow.Content = _action_content;
				objArow.CreateDate = DateTime.Now;
				using (MainDB objDb = new MainDB())
				{
					objDb.NewsCollection.Update(objrow);
					objDb.ActionCollection.Insert(objArow);
				}
			}
		}


		public static DataTable GetNewsListAction(string _news_id, int PageSize, int StartRow)
		{
			int k = 0;
			int intPageNum = StartRow / PageSize + 1;
			using (MainDB objDb = new MainDB())
			{
				return objDb.ActionCollection.GetAsDataTable(" news_id = '" + _news_id + "'", " createdate desc ", StartRow, PageSize, ref k);
			}
		}

		public static int GetCountAction(string _news_id)
		{
			using (MainDB objDb = new MainDB())
			{
				return Convert.ToInt32(objDb.ActionCollection.GetCount(" news_id = '" + _news_id + "'"));
			}
		}


		public static int GetCountNews(string strcpmod)
		{
            
            string strCats = CategoryHelper.GetCatIDByUser();
            
			if (strCats == "")
				return 0;

			string strWhere = "";

			switch (strcpmod.ToLower())
			{
				case "templist":
					strWhere = "News_Status=0 AND Cat_ID in (" + strCats + ")";
					break;
				case "sendlist":
				case "editwaitlist":
				case "editinglist":
					strWhere = "News_Status=1 AND Cat_ID in (" + strCats + ")";
					break;
				case "sendapprovallist":
				case "approvinglist":
				case "approvalwaitlist":
					strWhere = "News_Status=2 AND Cat_ID in (" + strCats + ")";
					break;
				case "dellist":
					strWhere = "News_Status=6 AND Cat_ID in (" + strCats + ")";
					break;
				case "publishedlist":
					strWhere = "News_Status=3 AND Cat_ID in (" + strCats + ")";
					break;
				case "backlist":
					strWhere = "News_Status=5 AND Cat_ID in (" + strCats + ")";
					break;
				case "removedlist":
					strWhere = "News_Status=7 AND Cat_ID in (" + strCats + ")";
					break;

			}

			return GetRowsNews(strWhere, strcpmod);
		}

        public static int CafeF_GetCountNews(string strcpmod, string user, Role objRole)
        {
            /* tiennv sua 20-05-2010 : lay count cua cac muc de hien thi tren menu (chu do) */
            
            string strCats = CategoryHelper.GetCatIDByUser();
            
            string strCatsPer = CategoryHelper.CafeF_GetCatIDByUser_Permission(user);
            if (strCats == "")
                return 0;

            string strWhere = "";

            switch (strcpmod.ToLower())
            {
                case "templist":
                    strWhere = "News_Status=0 AND Cat_ID in (" + strCats + ")";
                    //if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    //{
                    //    strWhere = "News_Status=0 AND Cat_ID in (" + strCats + ")";
                    //}
                    //else
                    //{
                    //    strWhere = "News_Status=0 AND Cat_ID in (" + strCats + ") and Sender_ID = '" + user + "' ";
                       
                    //}
                    
                    break;
                case "sendlist":
                case "editwaitlist":
                case "editinglist":
                    strWhere = "News_Status=1 AND Cat_ID in (" + strCats + ")";
                    //if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    //{
                    //    strWhere = "News_Status=1 AND Cat_ID in (" + strCats + ")";
                    //}
                    //else
                    //{
                    //    strWhere = "News_Status=1 AND Cat_ID in (" + strCats + ")  and Sender_ID = '" + user + "' ";                        
                    //}
                    
                    break;
                case "sendapprovallist":
                case "approvinglist":
                case "approvalwaitlist":
                    strWhere = "News_Status=2 AND Cat_ID in (" + strCats + ")";
                    //if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    //{
                    //    strWhere = "News_Status=2 AND Cat_ID in (" + strCats + ")";
                    //}
                    //else
                    //{
                    //    strWhere = "News_Status=2 AND Cat_ID in (" + strCats + ") and Sender_ID = '" + user + "' ";
                    //}
                    
                    break;
                case "dellist":
                    strWhere = "News_Status=6 AND Cat_ID in (" + strCats + ")";
                    //if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    //{
                    //    strWhere = "News_Status=6 AND Cat_ID in (" + strCats + ")";
                    //}
                    //else
                    //{
                    //    strWhere = "News_Status=6 AND Cat_ID in (" + strCats + ") and Sender_ID = '" + user + "' ";
                    //}
                    
                    break;
                case "publishedlist":
                    if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    {
                        strWhere = "News_Status=3 AND Cat_ID in (" + strCatsPer + ")";                       
                    }
                    else
                    {
                        strWhere = "News_Status=3 AND Cat_ID in (" + strCatsPer + ") ";
                        //strWhere = "News_Status=3 AND Cat_ID in (" + strCatsPer + ") and Sender_ID = '" + user + "' and ActionType = 3 ";
                        //strCats = " AND Cat_ID in (" + strCats + ") and Sender_ID = '" + user + "' and ActionType = 3 ";
                        //strAndCat = strCats + strAndCat;
                    }
                    break;
                case "allpublish":
                    strWhere = "News_Status=3 AND Cat_ID in (" + strCats + ")";
                    break;
                case "backlist":
                    strWhere = "News_Status=5 AND Cat_ID in (" + strCats + ")";
                    break;
                case "removedlist":
                    /* tiennv : 20-05-2010
                    strWhere = "News_Status=7 AND Cat_ID in (" + strCats + ")";
                    */
                    if (user == "channelvn" || user == "admin" || objRole.isThuKyChuyenMuc || objRole.isThuKyToaSoan || objRole.isPhuTrachKenh || objRole.isTongBienTap)
                    {
                        strWhere = "News_Status=7 AND Cat_ID in (" + strCatsPer + ")";
                    }
                    else
                    {
                        strWhere = "News_Status=7 AND Cat_ID in (" + strCatsPer + ") and Sender_ID = '" + user + "' ";
                    }
                    
                    break;

            }

            return CafeF_GetRowsNews(strWhere, strcpmod);
        }

        /*tiennv sua 20-05-2010 */

        public static int CafeF_GetRowsNews(string strWhere, string cpmode)
        {
            if (strWhere == null)
                strWhere = "";

            //if (cpmode == "allpublish")
            //    cpmode = "publishedlist";

            string strCacheName = "CafeF_GetRowsNews_" + cpmode + "_" + HttpContext.Current.User.Identity.Name;
            DataTable objresult = Portal.BO.Common.Utils.GetFromCache(strCacheName);
            if (objresult == null)
            {
                using (MainDB objdb = new MainDB())
                {
                    objresult = objdb.StoredProcedures.News_GetListNewNumRow(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name);
                }

                Portal.BO.Common.Utils.SetDataToCache(objresult, strCacheName, "Action");
            }
            return (int)objresult.Rows[0][0];
        }

		public static int GetRowsNews(string strWhere, string cpmode)
		{
			if (strWhere == null)
				strWhere = "";

			string strCacheName = "GetRowsNews_" + cpmode + "_" + HttpContext.Current.User.Identity.Name;
			DataTable objresult = Portal.BO.Common.Utils.GetFromCache(strCacheName);
			if (objresult == null)
			{
				using (MainDB objdb = new MainDB())
				{
					objresult = objdb.StoredProcedures.News_GetListNewNumRow(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name);
				}

				Portal.BO.Common.Utils.SetDataToCache(objresult, strCacheName, "Action");
			}
			return (int)objresult.Rows[0][0];
		}


		[DataObjectMethod(DataObjectMethodType.Select)]
		public static DataTable GetNewslistOfNewsListControl(string strWhere, int PageSize, int StartRow, string News_Approver, string SortExpression)
		{
			string cpmode = "";
			if (HttpContext.Current.Request.QueryString["cpmode"] != null)
				cpmode = HttpContext.Current.Request.QueryString["cpmode"].ToString();

			if (string.IsNullOrEmpty(SortExpression)) SortExpression = "[News].News_ModifiedDate DESC";
            if (cpmode.IndexOf("publishedlist") > -1) SortExpression = SortExpression.Replace("[News].News_ModifiedDate", "News.News_publishDate");

			//Lay gia tri mode list de xu ly
			if (strWhere == null)
				strWhere = "";

			DataTable objresult;
			int intPageNum = StartRow / PageSize + 1;
			//lay duoc du lieu cua tat ca nhung thang co trang thai la status can lay
			using (MainDB objdb = new MainDB())
			{
				//if (News_Approver == "" || News_Approver == null)
				//{
					objresult = objdb.StoredProcedures.News_GetListNew(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name, StartRow.ToString(), PageSize.ToString(), SortExpression);
				//}
				//else
				//{
				//	objresult = objdb.StoredProcedures.News_GetListNewMyPublished(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name, StartRow.ToString(), PageSize.ToString(), News_Approver, SortExpression);
				//}
			}
			return objresult;
		}

		public static int GetRowsCountOfNewsListControl(string strWhere, string News_Approver)
		{
            // tiennv sua : lay count cua bai da xuat ban 
			if (strWhere == null)
				strWhere = "";
			string cpmode = HttpContext.Current.Request.QueryString["cpmode"].ToString();
			DataTable objresult;
			using (MainDB objdb = new MainDB())
			{
				objresult = objdb.StoredProcedures.News_GetListNewNumRow(strWhere, cpmode, HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.Name);
			}
			return (int)objresult.Rows[0][0];
		}

		public static DataTable SelectNewsByRangeId(String RangeNewsId)
		{
			using (MainDB db = new MainDB())
			{
				DataTable table = db.StoredProcedures.vc_News_SelectListNewsByRangeNewsId(RangeNewsId);
				return table;
			}
		}


        [DataObjectMethod(DataObjectMethodType.Select)]
        public static DataTable News_GetAllNewsTemplist(string strWhere, int PageSize, int StartRow)
        {
            //Lay gia tri mode list de xu ly
            if (strWhere == null)
                strWhere = "";

            int EndIndex = PageSize + StartRow;

            DataTable objresult;
            
            using (MainDB objdb = new MainDB())
            {
                objresult = objdb.StoredProcedures.News_GetAllNewsTemplist(strWhere, StartRow.ToString(), EndIndex.ToString());
            }
            return objresult;
        }


        public static int News_GetAllNewsTemplistCount(string strWhere)
        {
            //Lay gia tri mode list de xu ly
            if (strWhere == null)
                strWhere = "";

            //lay duoc du lieu cua tat ca nhung thang co trang thai la status can lay
            using (MainDB objdb = new MainDB())
            {
                return Convert.ToInt32(objdb.StoredProcedures.News_GetAllNewsTemplistCount(strWhere).Rows[0][0]);
            }
            
        }

        

	}

	public enum NewsStatus : byte
	{
		LuuTam = 0,
		ChoBienTap = 1, NhanBienTap = 1,
		ChoDuyet = 2, NhanDuyet = 2,
		XuatBan = 3,
		TraLai = 5,
		XoaTam = 6,
		GoBo = 7,
		None = 255
	}
}
